// pages/pay-join/pay-join.js
import { Payment } from '../../models/payment'
import { RedPacket } from '../../models/redpacket'

let packetModel = new RedPacket()
const paymentModel = new Payment()

Page({
  /**
   * Page initial data
   */
  data: {
    showPassword: false,
    agreementChecked: false,
    password: '',
    canStick: false,
    countPrice: 0,
    step: 0,
    prevPage: {},
    dueDate: '',
    showPay: false,
    payInfo: {
      stickDay: 0
    },
    maxDays: 999,
    redPacketMoney: 0,
    payStatus: [
      {
        name: '微信支付'
      },
      {
        name: '好友代付'
      }
    ]
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function (options) {
    console.log(options.data)
    this.setData({
      'prevPage.data': JSON.parse(options.data),
      'prevPage.type': options.type,
      'prevPage.payType': options.payType
    })

    this.getPacketSize()
    wx.setNavigationBarTitle({
      title: options.payType || '入驻付费'
    })
  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function () {},

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function () {
    wx.showLoading({
      title: '加载中~'
    })
    this.checkStick()
  },

  toNewPage() {
    wx.navigateTo({
      url: '/pages/webview/webview'
    })
  },

  checkStick() {
    // 检查是否可以置顶
    paymentModel.checkStick(
      {
        type: this.data.prevPage.type
      },
      (res) => {
        this.setData({
          canStick: res
        })
        this.getPublishInfo()
      }
    )
  },

  onPay() {
    // 点击支付按钮
    if (!this.data.agreementChecked) {
      wx.showToast({
        title: '请先阅读并同意《充值服务协议》',
        icon: 'none'
      })
      return
    }
    this.setData({
      showPay: true
    })
  },

  getPublishInfo() {
    // 获取发布置顶价格等信息
    paymentModel.getPublishInfo(
      {
        name: this.data.prevPage.type
      },
      (res) => {
        this.setData({
          payInfo: {
            stickPrice: this.data.canStick ? res.stickPrice / res.stickDay : 0,
            issuePrice: +res.issuePrice,
            stickDay:
              this.data.prevPage.payType === '付费置顶' ? res.stickDay : 0
          },
          step: res.stickDay,
          countPrice:
            this.data.prevPage.payType === '付费置顶'
              ? +res.stickPrice
              : +res.issuePrice
        })
        wx.hideLoading()
      }
    )
  },

  wxPay() {
    // 微信支付
    const that = this
    wx.login({
      success(res) {
        if (res.code) {
          paymentModel.wxPay(
            {
              code: res.code,
              mapParam: {
                [that.data.prevPage.type]: that.data.prevPage.data
              },
              payMoney: that.data.countPrice,
              payType: that.getPayType(),
              stickNumber: that.data.payInfo.stickDay
            },
            (res) => {
              console.log('-------', res)
              wx.requestPayment({
                timeStamp: res.timeStamp,
                nonceStr: res.nonceStr,
                package: res.package,
                signType: res.signType,
                paySign: res.paySign,
                success(res) {
                  paymentModel.paySuccess({
                    code: res.code,
                    outTradeNo: res.out_trade_no,
                    mapParam: {
                      [that.data.prevPage.type]: that.data.prevPage.data
                    },
                    payMoney: that.data.countPrice,
                    payType: that.getPayType(),
                    stickNumber: that.data.payInfo.stickDay
                  })
                  wx.reLaunch({
                    url:
                      '/packageA/pages/pay-success/pay-success?desc=' +
                      that.getDesc() +
                      '&redpacket=' +
                      that.data.redPacketMoney
                  })
                },
                fail(res) {
                  console.log(res)
                  wx.showToast({
                    title: '支付失败，如有疑问请联系客服~',
                    icon: 'none'
                  })
                }
              })
            }
          )
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },

  payForAnother() {
    const that = this
    paymentModel.payForAnother(
      {
        key: that.data.prevPage.type,
        object: that.data.prevPage.data
      },
      (res) => {
        wx.navigateTo({
          url: `/pages/another/another?id=${res.id}&key=${res.key}&price=${that.data.countPrice}`
        })
      }
    )
  },
  getPayType() {
    return this.data.prevPage.payType === '付费置顶'
      ? 2
      : this.data.payInfo.stickDay > 0
      ? 3
      : 1
  },

  getDesc() {
    // 生成支付成功页的提示文字
    return this.data.prevPage.payType === '付费置顶'
      ? `置顶时间为${this.data.payInfo.stickDay}天`
      : this.data.payInfo.stickDay <= 0
      ? '平台将在24小时内完成审核，请耐心等待！'
      : `平台将在24小时内完成审核，请耐心等待！ \n ${
          this.data.payInfo.stickDay > 0
            ? `置顶时间为${this.data.payInfo.stickDay}天（审核通过后开始计算时间）`
            : ''
        }`
  },

  longTap() {
    // 长按触发 输入隐藏优惠码
    this.setData({
      showPassword: true
    })
  },

  onConfirm() {
    if (this.data.password == 'xianmai666') {
      wx.showToast({
        icon: 'none',
        title: `口令正确,已优惠${this.data.countPrice - 0.01}元`,
        duration: 3000
      })
      this.setData({
        countPrice: 0.01,
        showPassword: false
      })
    } else {
      this.setData({
        showPassword: false
      })
      wx.showToast({
        icon: 'none',
        title: '口令错误'
      })
    }
  },

  onClose() {
    this.setData({
      showPassword: false
    })
  },

  getPacketSize() {
    // 获取发红包返现金额
    packetModel.getPacketSize((res) => {
      res.forEach((item) => {
        if (item.modeName == this.data.prevPage.type) {
          this.setData({
            redPacketMoney: item.totalMoney
          })
        }
      })
    })
  },

  onChange(event) {
    if (!this.data.canStick) {
      this.setData({
        maxDays: 0
      })
      wx.showToast({
        title: '置顶名额已满，请待名额空余后再试！',
        icon: 'none',
        duration: 3000
      })
      return
    }
    this.setData({
      'payInfo.stickDay': event.detail,
      countPrice:
        this.data.prevPage.payType === '付费置顶'
          ? (this.data.payInfo.stickPrice * event.detail).toFixed(2)
          : (
              this.data.payInfo.issuePrice +
              this.data.payInfo.stickPrice * event.detail
            ).toFixed(2)
    })
    console.log(
      this.data.payInfo.stickPrice * this.data.payInfo.stickDay,
      this.data.payInfo.stickPrice,
      this.data.payInfo.stickDay
    )
  },

  onPayStatusSelect(e) {
    switch (e.detail.name) {
      case '微信支付':
        this.wxPay()
        break
      case '好友代付':
        this.payForAnother()
        break
    }
  },

  onAgreementChange(e) {
    this.setData({
      agreementChecked: e.detail
    })
  }
})
